<template>
	<view class="movie-edit-container">
		<view class="edit-form">
			<!-- 电影海报 -->
			<view class="form-section">
				<text class="section-title">电影海报</text>
				<view class="poster-upload">
					<image 
						v-if="movieForm.poster" 
						:src="movieForm.poster" 
						class="poster-preview" 
						mode="aspectFill"
						@click="choosePoster"
					></image>
					<view v-else class="poster-placeholder" @click="choosePoster">
						<uni-icons type="camera" size="40" color="#cccccc"></uni-icons>
						<text class="placeholder-text">点击选择海报</text>
					</view>
				</view>
			</view>

			<!-- 基本信息 -->
			<view class="form-section">
				<text class="section-title">基本信息</text>
				<view class="form-item">
					<text class="form-label">电影名称 *</text>
					<uni-easyinput
						v-model="movieForm.title"
						placeholder="请输入电影名称"
						:styles="inputStyles"
					></uni-easyinput>
				</view>

				<view class="form-item">
					<text class="form-label">上映年份 *</text>
					<uni-easyinput
						v-model="movieForm.year"
						placeholder="请输入上映年份"
						:styles="inputStyles"
					></uni-easyinput>
				</view>

				<view class="form-item">
					<text class="form-label">电影分类 *</text>
					<picker 
						:value="categoryIndex" 
						:range="categoryOptions" 
						range-key="name"
						@change="onCategoryChange"
					>
						<view class="picker-input">
							{{ categoryOptions[categoryIndex]?.name || '请选择分类' }}
							<uni-icons type="bottom" size="14" color="#999999"></uni-icons>
						</view>
					</picker>
				</view>

				<view class="form-item">
					<text class="form-label">评分 *</text>
					<uni-easyinput
						v-model="movieForm.rating"
						type="number"
						placeholder="请输入评分 (0-10)"
						:styles="inputStyles"
					></uni-easyinput>
				</view>

				<view class="form-item">
					<text class="form-label">时长</text>
					<uni-easyinput
						v-model="movieForm.duration"
						placeholder="请输入电影时长，如：120分钟"
						:styles="inputStyles"
					></uni-easyinput>
				</view>
			</view>

			<!-- 详细信息 -->
			<view class="form-section">
				<text class="section-title">详细信息</text>
				<view class="form-item">
					<text class="form-label">导演</text>
					<uni-easyinput
						v-model="movieForm.director"
						placeholder="请输入导演姓名"
						:styles="inputStyles"
					></uni-easyinput>
				</view>

				<view class="form-item">
					<text class="form-label">主演</text>
					<view class="cast-input">
						<uni-easyinput
							v-model="castInput"
							placeholder="请输入演员姓名，按回车添加"
							:styles="inputStyles"
							@confirm="addCast"
						></uni-easyinput>
						<button class="add-cast-btn" @click="addCast">添加</button>
					</view>
					<view class="cast-list" v-if="movieForm.cast && movieForm.cast.length > 0">
						<view 
							v-for="(actor, index) in movieForm.cast" 
							:key="index" 
							class="cast-item"
						>
							<text class="cast-name">{{ actor }}</text>
							<button class="remove-cast-btn" @click="removeCast(index)">
								<uni-icons type="close" size="14" color="#f44336"></uni-icons>
							</button>
						</view>
					</view>
				</view>

				<view class="form-item">
					<text class="form-label">电影简介</text>
					<textarea
						v-model="movieForm.description"
						placeholder="请输入电影简介"
						class="description-input"
						maxlength="500"
						show-confirm-bar="false"
					></textarea>
					<text class="char-count">{{ movieForm.description?.length || 0 }}/500</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="form-actions">
				<button class="cancel-btn" @click="handleCancel">取消</button>
				<button class="save-btn" @click="handleSave" :disabled="!canSave">
					{{ isEditMode ? '更新电影' : '添加电影' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import { useMovieStore } from '@/stores/movie.js'
import { useUserStore } from '@/stores/user.js'

export default {
	data() {
		return {
			mode: 'add', // add 或 edit
			movieId: null,
			movieForm: {
				title: '',
				year: '',
				rating: '',
				category: '',
				poster: '',
				description: '',
				duration: '',
				director: '',
				cast: []
			},
			castInput: '',
			categoryIndex: 0,
			inputStyles: {
				color: '#333333',
				backgroundColor: '#f8f8f8',
				borderColor: '#e0e0e0'
			}
		}
	},
	setup() {
		const movieStore = useMovieStore()
		const userStore = useUserStore()
		return {
			movieStore,
			userStore
		}
	},
	onLoad(options) {
		this.checkAdminPermission()
		this.mode = options.mode || 'add'
		this.movieId = options.movieId ? parseInt(options.movieId) : null

		// 初始化电影数据
		this.movieStore.initMovieData()

		if (this.isEditMode && this.movieId) {
			this.loadMovieData()
		} else {
			// 添加模式下设置默认分类
			this.initAddMode()
		}
	},
	computed: {
		isEditMode() {
			return this.mode === 'edit'
		},
		categoryOptions() {
			// 过滤掉"全部"分类
			return this.movieStore.categories.filter(c => c.id !== 'all')
		},
		canSave() {
			const rating = parseFloat(this.movieForm.rating)
			return this.movieForm.title.trim() &&
				   this.movieForm.year.trim() &&
				   this.movieForm.rating &&
				   this.movieForm.category &&
				   !isNaN(rating) &&
				   rating >= 0 &&
				   rating <= 10
		}
	},
	methods: {
		// 检查管理员权限
		checkAdminPermission() {
			this.userStore.initUserData()
			
			if (!this.userStore.isAdmin) {
				uni.showModal({
					title: '权限不足',
					content: '您没有管理员权限，无法访问此页面',
					showCancel: false,
					success: () => {
						uni.navigateBack()
					}
				})
				return false
			}
			return true
		},

		// 初始化添加模式
		initAddMode() {
			// 设置默认分类为第一个可用分类
			if (this.categoryOptions.length > 0) {
				this.categoryIndex = 0
				this.movieForm.category = this.categoryOptions[0].id
			}
		},

		// 加载电影数据（编辑模式）
		loadMovieData() {
			const movie = this.movieStore.getMovieById(this.movieId)

			if (movie) {
				this.movieForm = {
					title: movie.title || '',
					year: movie.year || '',
					rating: movie.rating?.toString() || '',
					category: movie.category || '',
					poster: movie.poster || '',
					description: movie.description || '',
					duration: movie.duration || '',
					director: movie.director || '',
					cast: movie.cast ? [...movie.cast] : []
				}

				// 设置分类索引
				this.categoryIndex = this.categoryOptions.findIndex(c => c.id === movie.category)
				if (this.categoryIndex === -1) this.categoryIndex = 0
			} else {
				uni.showModal({
					title: '错误',
					content: '电影不存在',
					showCancel: false,
					success: () => {
						uni.navigateBack()
					}
				})
			}
		},

		// 选择海报
		choosePoster() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.movieForm.poster = res.tempFilePaths[0]
				},
				fail: () => {
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					})
				}
			})
		},

		// 分类选择变化
		onCategoryChange(e) {
			this.categoryIndex = e.detail.value
			this.movieForm.category = this.categoryOptions[this.categoryIndex].id
		},

		// 添加演员
		addCast() {
			if (this.castInput.trim()) {
				if (!this.movieForm.cast) {
					this.movieForm.cast = []
				}
				if (!this.movieForm.cast.includes(this.castInput.trim())) {
					this.movieForm.cast.push(this.castInput.trim())
					this.castInput = ''
				} else {
					uni.showToast({
						title: '演员已存在',
						icon: 'none'
					})
				}
			}
		},

		// 移除演员
		removeCast(index) {
			this.movieForm.cast.splice(index, 1)
		},

		// 取消操作
		handleCancel() {
			uni.showModal({
				title: '确认取消',
				content: '确定要取消编辑吗？未保存的内容将丢失。',
				success: (res) => {
					if (res.confirm) {
						uni.navigateBack()
					}
				}
			})
		},

		// 保存电影
		handleSave() {
			console.log('保存电影 - 表单数据:', this.movieForm)
			console.log('canSave:', this.canSave)
			console.log('分类选项:', this.categoryOptions)
			console.log('当前分类索引:', this.categoryIndex)

			if (!this.canSave) {
				console.log('保存失败 - 必填信息不完整')
				console.log('标题:', this.movieForm.title.trim())
				console.log('年份:', this.movieForm.year.trim())
				console.log('评分:', this.movieForm.rating)
				console.log('分类:', this.movieForm.category)

				uni.showToast({
					title: '请完善必填信息',
					icon: 'none'
				})
				return
			}

			// 验证评分范围
			const rating = parseFloat(this.movieForm.rating)
			if (rating < 0 || rating > 10) {
				uni.showToast({
					title: '评分必须在0-10之间',
					icon: 'none'
				})
				return
			}

			// 准备保存的数据
			const movieData = {
				title: this.movieForm.title.trim(),
				year: this.movieForm.year.trim(),
				rating: rating,
				category: this.movieForm.category,
				poster: this.movieForm.poster || '/static/logo.png',
				description: this.movieForm.description?.trim() || '',
				duration: this.movieForm.duration?.trim() || '',
				director: this.movieForm.director?.trim() || '',
				cast: this.movieForm.cast || []
			}

			let result
			if (this.isEditMode) {
				result = this.movieStore.updateMovie(this.movieId, movieData)
			} else {
				result = this.movieStore.addMovie(movieData)
			}

			if (result.success) {
				uni.showToast({
					title: result.message,
					icon: 'success'
				})
				
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} else {
				uni.showToast({
					title: result.message,
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style scoped>
.movie-edit-container {
	background: #f5f5f5;
	min-height: 100vh;
	padding: 30rpx;
}

.edit-form {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
}

.form-section {
	padding: 40rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-section:last-child {
	border-bottom: none;
}

.section-title {
	display: block;
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 30rpx;
}

.poster-upload {
	text-align: center;
}

.poster-preview {
	width: 200rpx;
	height: 280rpx;
	border-radius: 10rpx;
	border: 2rpx dashed #e0e0e0;
}

.poster-placeholder {
	width: 200rpx;
	height: 280rpx;
	border: 2rpx dashed #e0e0e0;
	border-radius: 10rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin: 0 auto;
}

.placeholder-text {
	margin-top: 20rpx;
	font-size: 26rpx;
	color: #999999;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-item:last-child {
	margin-bottom: 0;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 15rpx;
}

.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background: #f8f8f8;
	border: 1rpx solid #e0e0e0;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #333333;
}

.cast-input {
	display: flex;
	gap: 15rpx;
	align-items: center;
}

.cast-input .uni-easyinput {
	flex: 1;
}

.add-cast-btn {
	padding: 20rpx 30rpx;
	background: #ff6b35;
	color: white;
	border: none;
	border-radius: 10rpx;
	font-size: 26rpx;
	white-space: nowrap;
}

.cast-list {
	margin-top: 20rpx;
	display: flex;
	flex-wrap: wrap;
	gap: 15rpx;
}

.cast-item {
	display: flex;
	align-items: center;
	gap: 10rpx;
	padding: 10rpx 15rpx;
	background: #f0f0f0;
	border-radius: 20rpx;
}

.cast-name {
	font-size: 26rpx;
	color: #333333;
}

.remove-cast-btn {
	background: none;
	border: none;
	padding: 5rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.description-input {
	width: 100%;
	min-height: 200rpx;
	padding: 20rpx;
	background: #f8f8f8;
	border: 1rpx solid #e0e0e0;
	border-radius: 10rpx;
	font-size: 28rpx;
	color: #333333;
	resize: none;
}

.char-count {
	display: block;
	text-align: right;
	margin-top: 10rpx;
	font-size: 24rpx;
	color: #999999;
}

.form-actions {
	display: flex;
	gap: 30rpx;
	padding: 40rpx 30rpx;
}

.cancel-btn, .save-btn {
	flex: 1;
	height: 88rpx;
	border-radius: 44rpx;
	font-size: 32rpx;
	border: none;
}

.cancel-btn {
	background: #f5f5f5;
	color: #666666;
}

.save-btn {
	background: linear-gradient(45deg, #ff6b35, #ff8c42);
	color: white;
}

.save-btn:disabled {
	background: #cccccc;
	color: #999999;
}
</style>
